package com.axin.web.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.axin.blog.api.RemoteWebUserService;
import com.axin.blog.api.domain.WebUser;
import com.axin.common.core.domain.model.LoginBody;
import com.axin.common.core.domain.web.AjaxResult;
import com.axin.common.core.exception.ServiceException;
import com.axin.common.core.utils.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author axin
 * @Date 2021/11/7 10:56
 **/
@Service
public class WebLoginService {

    @Autowired
    private RemoteWebUserService webUserService;

    @Autowired
    private WebTokenService webTokenService;

    /**
     * 登录验证
     *
     * @param loginBody 用户登录表单填写信息
     * @return
     */
    public String login(LoginBody loginBody) {

        AjaxResult<WebUser> result = webUserService.infoByUsername(loginBody.getUserName());
        if (!result.isSuccess()) {
            throw new ServiceException("博客服务未启动");
        }
        if (ObjectUtil.isNull(result.getData())){
            throw new ServiceException("账号不存在");
        }
        WebUser user = result.getData();
        if (!StrUtil.equals(SecureUtil.md5(loginBody.getPassword()), user.getPassword())) {
            throw new ServiceException("密码错误");
        }
        // 记录登录信息
        recordLoginInfo(user);

        // 生成token
        return webTokenService.createToken(user);
    }


    public AjaxResult register(WebUser user) {

        return webUserService.register(user);
    }

    /**
     * 记录登录信息
     *
     * @param user 用户
     */
    public void recordLoginInfo(WebUser user) {
        UserAgent userAgent = UserAgentUtil.parse(ServletUtils.getRequest().getHeader("User-Agent"));
        user.setLoginCount(user.getLoginCount() + 1);
        user.setLoginIp(ServletUtils.getClientIP());
        user.setLoginDate(new Date());
        user.setBrowser(userAgent.getBrowser().getName());
        user.setOs(userAgent.getOs().getName());
        webUserService.updateUserProfile(user);

    }

    /**
     * 退出登录
     *
     * @param request
     */
    public void logout(HttpServletRequest request) {

        String token = webTokenService.getToken(request);
        webTokenService.delLoginUser(token);
    }
}
